package com.rogge.plugin;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import dalvik.system.DexClassLoader;

/**
 * [Description]
 * <p>
 * [How to use]
 * <p>
 * [Tips]
 *
 * @author Created by Rogge on 2018/5/6 0006.
 * @since 1.0.0
 */

public class PluginManager {

    private DexClassLoader dexClassLoader;

    private Resources resources;

    private Resources.Theme theme;

    private Context context;

    private String entryActivityName;

    private static final PluginManager ourInstance = new PluginManager();

    public static PluginManager getInstance() {
        return ourInstance;
    }

    private PluginManager() {

    }

    public void loadPath(String path){
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo = packageManager.getPackageArchiveInfo(path,PackageManager.GET_ACTIVITIES);
        entryActivityName = packageInfo.activities[0].name;
        File dexOutFile = context.getDir("dex", Context.MODE_PRIVATE);
        dexClassLoader = new DexClassLoader(path,dexOutFile.getAbsolutePath(),null,context.getClassLoader());
        try {
            AssetManager assetManager = AssetManager.class.newInstance();
            Method addAsset = AssetManager.class.getMethod("addAssetPath",String.class);
            addAsset.invoke(assetManager,path);
            resources = new Resources(assetManager,context.getResources().getDisplayMetrics(),context.getResources().getConfiguration());
            theme = resources.newTheme();
            theme.setTo(context.getTheme());
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public DexClassLoader getDexClassLoader() {
        return dexClassLoader;
    }

    public Resources getResources() {
        return resources;
    }

    public void setContext(Context context) {
        this.context = context.getApplicationContext();
    }

    public String getEntryActivityName() {
        return entryActivityName;
    }

    public Resources.Theme getTheme() {
        return theme;
    }
}
